package com.hjw.httpclient.demo;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.yaml.snakeyaml.util.UriEncoder;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 手动对请求参数进行一次 urlencode 编码
 *
 * @author hjwStrart
 * @time 2022-11-09 20:25
 * @version: 1.0
 */
public class Demo3 {

    @Test
    public void method1() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String userPwd = "hjw+123";
        // 对请求参数进行  urlencode 编码
        // 使用JDK原生API URLEncoder 对请求参数进行编码
        String encodeUserPwd = null;
        try {
            encodeUserPwd = URLEncoder.encode(userPwd, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://localhost:8080/form/get?userName=admin&userPwd=" + encodeUserPwd;
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = null;
        BufferedReader br = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            // 标识本次请求的状态（成功、失败）
            StatusLine statusLine = httpResponse.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("相应成功");
                // 获取响应头
                Header[] headers = httpResponse.getAllHeaders();
                for (Header header : headers) {
                    System.out.println("请求头" + header.getName() + "的值" + header.getValue());
                }
                HttpEntity entity = httpResponse.getEntity();
                // 通过HttpEntity可以直接获取到ContentType
                Header contentType = entity.getContentType();
                System.out.println("ContentType:" + contentType.getValue());
                InputStream is = entity.getContent();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                br = new BufferedReader(isr);
                String tempStr;
                StringBuilder result = new StringBuilder();
                while ((tempStr = br.readLine()) != null) {
                    result.append(tempStr);
                }
                System.out.println(result); // userName=admin,userPwd=hjw 123
                // 此时可以看到，服务器接收的请求参数和客户端输入的参数不一致
                // 因此，当我们使用HttpClient模拟浏览器发送请求时，需要对请求参数进行一次 urlencode 编码
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
